<template>
  <view class="nickname-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image class="back-icon" src="/static/Images/user/Fanhui.png" mode="aspectFit"></image>
      </view>
      <view class="title">修改昵称</view>
    </view>
    
    <!-- 输入区域 -->
    <view class="input-container">
      <view class="input-wrapper">
        <input 
          class="nickname-input" 
          type="text" 
          v-model="nickname" 
          placeholder="请输入您的昵称" 
          maxlength="24"
          @input="handleInput"
        />
        <view class="clear-btn" v-if="nickname" @click="clearInput">
          <image class="clear-icon" src="/static/Images/user/Shanchu.png" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- 字数限制提示 -->
      <view class="limit-tip">
        限4~24个字符（1汉字=2字符，1英文或数字=1字符）
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <view 
      class="save-btn" 
      :class="{ 'disabled': !isValid }" 
      @click="saveNickname"
    >
      保存
    </view>
    
    <!-- 底部安全区域 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { userApi } from '@/utils/api';

// 昵称
const nickname = ref('');

// 计算昵称是否有效
const isValid = computed(() => {
  // 计算字符长度（汉字算2个字符，英文和数字算1个字符）
  const length = [...nickname.value].reduce((total, char) => {
    return total + (/[\u4e00-\u9fa5]/.test(char) ? 2 : 1);
  }, 0);
  
  return length >= 4 && length <= 24;
});

// 处理输入
const handleInput = () => {
  // 可添加额外输入处理
};

// 清除输入
const clearInput = () => {
  nickname.value = '';
};

// 保存昵称
const saveNickname = async () => {
  if (!isValid.value) return;

  try {
    uni.showLoading({ title: '保存中...' });

    // 后端有的叫 nick_name，有的叫 nickname，统一同时传递，后端取其一
    const payload = {
      nick_name: nickname.value,
      nickname: nickname.value,
    };

    const res = await userApi.changeUserInfo(payload);

    // 兼容成功判断：res.success/res.code
    const ok = (res && (res.success === true || res.code === 200 || res.code === 1));
    if (!ok) {
      const msg = (res && (res.msg || res.message)) || '保存失败';
      throw new Error(msg);
    }

    uni.hideLoading();
    uni.showToast({ title: '保存成功', icon: 'success' });

    // 返回上一页并刷新
    setTimeout(async () => {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage && prevPage.route && typeof prevPage.onShow === 'function') {
        // 如果上一页实现了获取用户信息的方法，优先调用
        if (prevPage.$vm && typeof prevPage.$vm.fetchUserInfo === 'function') {
          try { await prevPage.$vm.fetchUserInfo(); } catch (e) {}
        }
        // 微信小程序/uniapp 页面钩子
        try { prevPage.onShow(); } catch (e) {}
      }
      uni.navigateBack();
    }, 800);
  } catch (err) {
    uni.hideLoading();
    uni.showToast({ title: err.message || '保存失败', icon: 'none' });
  }
};

// 返回用户主页
const navigateBack = () => {
  uni.navigateTo({
    url: '/pages/users/index'
  });
};
</script>

<style lang="scss">
.nickname-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 导航栏 */
/* #ifdef MP-WEIXIN */
.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  background-color: #ffffff;
  padding-top: 88rpx;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}
/* #endif */

/* 输入区域 */
.input-container {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
}

.nickname-input {
  flex: 1;
  height: 60rpx;
  font-size: 30rpx;
  color: #333;
}

.clear-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-icon {
  width: 40rpx;
  height: 40rpx;
}

.limit-tip {
  font-size: 28rpx;
  color: #FF9500;
  margin-top: 20rpx;
  padding: 0 10rpx;
}

/* 保存按钮 */
.save-btn {
  margin: 60rpx 30rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
  background-color: #FF3037;
  color: #fff;
}

.save-btn.disabled {
  background-color: #cccccc;
  color: #ffffff;
}

.safe-area-bottom {
  height: env(safe-area-inset-bottom);
}
</style>